package com.example.springboot_jap_model.service.Impl;

import com.example.springboot_jap_model.constant.Constant;
import com.example.springboot_jap_model.dao.AuthorityDao;
import com.example.springboot_jap_model.dao.RoleAndAuthorityDao;
import com.example.springboot_jap_model.dao.RoleDao;
import com.example.springboot_jap_model.dao.UserAndRoleDao;
import com.example.springboot_jap_model.domain.*;
import com.example.springboot_jap_model.enums.RespEntityEnum;
import com.example.springboot_jap_model.service.AuthService;
import com.example.springboot_jap_model.utils.PageableUtils;
import com.example.springboot_jap_model.utils.ParameterCheckUtils;
import com.example.springboot_jap_model.utils.RespEntityUtils;
import com.example.springboot_jap_model.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.configurationprocessor.json.JSONArray;
import org.springframework.boot.configurationprocessor.json.JSONException;
import org.springframework.boot.configurationprocessor.json.JSONObject;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.ui.ModelMap;
import org.thymeleaf.util.ListUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
public class AuthServiceImpl implements AuthService {
    @Autowired
    private AuthorityDao authorityDao;
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private RoleAndAuthorityDao roleAndAuthorityDao;
    @Autowired
    private UserAndRoleDao userAndRoleDao;

    private final static Logger logger = LoggerFactory.getLogger(AuthServiceImpl.class);

    @Override
    public RespEntity addAuthority(Authority authority) {
        if (ParameterCheckUtils.authCheck(authority)){
            //1.查询是否存在 存在 则更新
            Authority authorityOld = authorityDao.findFirstByUrl(authority.getUrl());
            if (authorityOld != null) {
                authorityOld.setName(authority.getName());
                authorityDao.save(authorityOld);
            } else {
                authorityDao.save(authority);
            }
            return RespEntityUtils.success(RespEntityEnum.SUCCESS);
        }
        return RespEntityUtils.error(RespEntityEnum.PARAMETER_EXCEPTION);
    }

    @Override
    public RespEntity generateRole(Long roleId,String authId) {
        //判断 role 是否存在
        Role role = roleDao.findById(roleId).get();
        if (role != null){
            // 生成 role and auth
            Long[] ints = StringUtil.interception(authId);
            //将老的 role and auth 删除
            List<RoleAndAuthority> roleAndAuthorityList = roleAndAuthorityDao.findByRoleId(roleId);
            if (!ListUtils.isEmpty(roleAndAuthorityList)){
                roleAndAuthorityDao.deleteAll(roleAndAuthorityList);
            }
            //创建 role and auth
            List<RoleAndAuthority> roleAndAuthorityListNew = new ArrayList<>();
            for (Long integer : ints) {
                roleAndAuthorityListNew.add(new RoleAndAuthority(roleId,integer));
            }
            if (!ListUtils.isEmpty(roleAndAuthorityListNew)) {
                roleAndAuthorityDao.saveAll(roleAndAuthorityListNew);
            }
            return RespEntityUtils.success(RespEntityEnum.SUCCESS);
        }
        return RespEntityUtils.error(RespEntityEnum.PARAMETER_EXCEPTION);
    }


    @Override
    public RespEntity assortRole(Long userId,Long roleId) {
        UserAndRole userAndRole = new UserAndRole(userId,roleId);
        if (!ParameterCheckUtils.userAndRoleCheck(userAndRole)){
            return RespEntityUtils.error(RespEntityEnum.PARAMETER_EXCEPTION);
        }
        List<UserAndRole> userAndRoleListOld = userAndRoleDao.findByUserId(userId);
        if (!ListUtils.isEmpty(userAndRoleListOld)){
            logger.info("删除 已存在 的 user and role  userId:{}",userId);
            userAndRoleDao.deleteAll(userAndRoleListOld);
        }
        userAndRoleDao.save(userAndRole);
        return RespEntityUtils.success(RespEntityEnum.SUCCESS);
    }

    /**
     * 查询所有保存的权限
     * @param modelMap
     * @param pageable
     */
    @Override
    public void findAllAuth(ModelMap modelMap, Pageable pageable) throws JSONException {
        //一级
        List<Authority> authorityLeve1 = authorityDao.findByLevel(Constant.LEVE_1);
        if (!ListUtils.isEmpty(authorityLeve1)){
            for (Authority authority : authorityLeve1){
                List<Authority> authorityList = authorityDao.findAllByParentsId(authority.getId());
                authority.setAuthorities(authorityList);
            }
        }
        modelMap.addAttribute("auth_p_list",authorityLeve1);
    }

    @Override
    public RespEntity findAllAuth(ModelMap modelMap) throws JSONException {
        List<Authority> authorityLeve1 = authorityDao.findByLevel(Constant.LEVE_1);
        if (!ListUtils.isEmpty(authorityLeve1)){
            for (Authority authority : authorityLeve1){
                List<Authority> authorityList = authorityDao.findAllByParentsId(authority.getId());
                authority.setAuthorities(authorityList);
            }
        }
        modelMap.addAttribute("auth_p_list",authorityLeve1);
        return RespEntityUtils.success(modelMap);
    }

    /**
     * 查询全部的 role
     * 1.并查出 对应的第一组的 auth
     * @param modelMap
     * @param pageable
     */
    @Override
    public void findAllRoleAndAuth(ModelMap modelMap, Pageable pageable) {
        List<Role> roleList = roleDao.findAll();
        if(!ListUtils.isEmpty(roleList)){
            modelMap.addAttribute("roleList",roleList);
            Role role = roleList.get(0);
            //查询 对应的 auth
            List<RoleAndAuthority> roleAndAuthorityList = roleAndAuthorityDao.findByRoleId(role.getId());
            if (!ListUtils.isEmpty(roleAndAuthorityList)){
                Long[] longs = {};
                for (int i=0;i<roleAndAuthorityList.size();i++){
                    longs[i] = roleAndAuthorityList.get(i).getAuthId();
                }
                List<Authority> authorityList = authorityDao.findByIdIn(longs);
                modelMap.addAttribute("authList",authorityList);
            }
        }

    }
}
